package com.walle.concurrenttest.actomic;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author zhangjiapeng
 * @Package com.walle.concurrenttest.actomic
 * @Description: ${todo}
 * @date 2019/2/15 13:44
 */
public class Consumer implements Runnable{

    private AtomicInteger storage;


    public Consumer(AtomicInteger storage) {
        this.storage = storage;
    }

    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see Thread#run()
     */
    @Override
    public void run() {
        while (true){
            int currentStorage = storage.get();
            if( currentStorage> 0){
                currentStorage = storage.decrementAndGet();
                String tName = Thread.currentThread().getName();
                System.out.println(String.format("消费者%s消费一个产品，当前剩余%d",tName,currentStorage));
                try {
                    Thread.sleep(300);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
